'use strict';

const crypto = require('crypto');
const { WXBizDataCrypt } = require('./WXBizDataCrypt');
const db = uniCloud.database();
const usersCollection = db.collection('users');

// 微信小程序配置
const wxConfig = {
  appid: 'wx2ec4b81ee78ef1b1', // 请将此处替换为您的微信小程序AppID
  appSecret: 'cc0ae2b43ae64f2870dcb92a4d0dd09f' // 请将此处替换为您的微信小程序AppSecret
};

exports.main = async (event, context) => {
  try {
    // 接收前端参数
    const { code, userInfo } = event;
    
    if (!code) {
      return {
        code: -1,
        message: '缺少code参数'
      };
    }
    
    // 获取openid和session_key
    let wxResult;
    try {
      wxResult = await getWxOpenId(code);
      
      if (!wxResult.openid || !wxResult.session_key) {
        return {
          code: -1,
          message: '获取openid失败'
        };
      }
    } catch (wxError) {
      console.error('获取微信信息失败:', wxError);
      return {
        code: -1,
        message: '获取微信信息失败: ' + wxError.message
      };
    }
    
    const { openid, session_key } = wxResult;
    
    // 查询是否已存在用户
    let userRecord;
    try {
      userRecord = await usersCollection.where({
        openid: openid
      }).get();
    } catch (dbError) {
      console.error('数据库查询失败：', dbError);
      return {
        code: -1,
        message: '数据库查询失败: ' + dbError.message
      };
    }
    
    let userId;
    
    try {
      if (userRecord.data && userRecord.data.length > 0) {
        // 更新已有用户信息
        userId = userRecord.data[0]._id;
        
        // 如果前端传了用户信息，就更新
        const updateData = {
          last_login_time: new Date(),
          update_time: new Date()
        };
        
        // 更新头像昵称（如果传了的话）
        if (userInfo) {
          if (userInfo.nickName) updateData.nickName = userInfo.nickName;
          if (userInfo.avatarUrl) updateData.avatar = userInfo.avatarUrl;
        }
        
        await usersCollection.doc(userId).update(updateData);
      } else {
        // 创建新用户
        const newUser = {
          openid: openid,
          unionid: wxResult.unionid || '',
          nickName: userInfo?.nickName || '新用户',
          avatar: userInfo?.avatarUrl || '',
          gender: 0,
          country: '',
          province: '',
          city: '',
          create_time: new Date(),
          update_time: new Date(),
          last_login_time: new Date(),
          cycle_records: [], // 经期记录
          cycle_count: 0     // 经期周期计数
        };
        
        const insertResult = await usersCollection.add(newUser);
        userId = insertResult.id;
      }
    } catch (userError) {
      console.error('用户数据操作失败：', userError);
      return {
        code: -1,
        message: '用户数据操作失败: ' + userError.message
      };
    }
    
    // 生成token
    const token = generateToken(userId, openid);
    
    // 查询最新的用户信息
    let latestUserInfo;
    try {
      latestUserInfo = await usersCollection.doc(userId).get();
    } catch (getUserError) {
      console.error('获取最新用户信息失败：', getUserError);
      // 即使获取最新用户信息失败，也返回基本登录信息
      return {
        code: 0,
        message: 'success',
        data: {
          userId: userId,
          openid: openid,
          token: token,
          cycle_count: 0
        }
      };
    }
    
    // 返回结果
    return {
      code: 0,
      message: 'success',
      data: {
        userId: userId,
        openid: openid,
        token: token,
        cycle_count: latestUserInfo.data.cycle_count || 0
      }
    };
    
  } catch (error) {
    console.error('微信登录失败：', error);
    return {
      code: -1,
      message: '微信登录失败：' + error.message
    };
  }
};

/**
 * 请求微信API获取openid和session_key
 * @param {string} code 
 * @returns {object} 
 */
async function getWxOpenId(code) {
  const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${wxConfig.appid}&secret=${wxConfig.appSecret}&js_code=${code}&grant_type=authorization_code`;
  
  try {
    const res = await uniCloud.httpclient.request(url, {
      method: 'GET',
      dataType: 'json'
    });
    
    if (res.status === 200) {
      if (res.data.errcode) {
        throw new Error(`微信返回错误：${res.data.errcode} - ${res.data.errmsg}`);
      }
      return {
        openid: res.data.openid,
        session_key: res.data.session_key,
        unionid: res.data.unionid
      };
    } else {
      throw new Error('微信服务器响应错误');
    }
  } catch (error) {
    console.error('获取openid失败:', error);
    throw error;
  }
}

/**
 * 生成JWT Token
 * @param {string} userId 
 * @param {string} openid 
 * @returns {string}
 */
function generateToken(userId, openid) {
  // 简单token生成，实际项目建议使用JWT库
  const header = {
    alg: 'HS256',
    typ: 'JWT'
  };
  
  const payload = {
    userId: userId,
    openid: openid,
    exp: Math.floor(Date.now() / 1000) + (7 * 24 * 60 * 60), // 7天过期
    iat: Math.floor(Date.now() / 1000)
  };
  
  const headerBase64 = Buffer.from(JSON.stringify(header)).toString('base64');
  const payloadBase64 = Buffer.from(JSON.stringify(payload)).toString('base64');
  
  const signature = crypto
    .createHmac('sha256', 'pink-diary-secret-key') // 请替换为您的密钥
    .update(`${headerBase64}.${payloadBase64}`)
    .digest('base64');
  
  return `${headerBase64}.${payloadBase64}.${signature}`;
} 